package com.ekuaitu.kuaitu.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.Polygon;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.adapter.ParkDetailPagerAdapter;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.AdPopBean;
import com.ekuaitu.kuaitu.bean.AdTopBean;
import com.ekuaitu.kuaitu.bean.AnimalEvent;
import com.ekuaitu.kuaitu.bean.BaseBean;
import com.ekuaitu.kuaitu.bean.BikeAroundBean;
import com.ekuaitu.kuaitu.bean.CancelOrder;
import com.ekuaitu.kuaitu.bean.CheckCarOrderBean;
import com.ekuaitu.kuaitu.bean.CityDetailBean;
import com.ekuaitu.kuaitu.bean.ConfirmCertifyBean;
import com.ekuaitu.kuaitu.bean.GetRemindBean;
import com.ekuaitu.kuaitu.bean.InitBean;
import com.ekuaitu.kuaitu.bean.MsgRedBean;
import com.ekuaitu.kuaitu.bean.NearCarBean;
import com.ekuaitu.kuaitu.bean.OperateBean;
import com.ekuaitu.kuaitu.bean.OrderDetailBean;
import com.ekuaitu.kuaitu.bean.ParkBean;
import com.ekuaitu.kuaitu.bean.ParkDetailBean;
import com.ekuaitu.kuaitu.bean.RedBikeHotSpotInfoBean;
import com.ekuaitu.kuaitu.bean.ResultBean;
import com.ekuaitu.kuaitu.bean.ScanSussEvent;
import com.ekuaitu.kuaitu.bean.ShakeResultBean;
import com.ekuaitu.kuaitu.bean.UnFinishOrderBean;
import com.ekuaitu.kuaitu.map.GeocodeSearchViewUtils;
import com.ekuaitu.kuaitu.map.MarkerUtils;
import com.ekuaitu.kuaitu.map.PolylineBoundUtils;
import com.ekuaitu.kuaitu.map.RoutePlanUtils;
import com.ekuaitu.kuaitu.map.SensorEventHelper;
import com.ekuaitu.kuaitu.utils.AccountStatus;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.DensityUtils;
import com.ekuaitu.kuaitu.utils.ImageLoader;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.LoadingDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SetRemindTimeDialog;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.utils.VerControlUtils;
import com.ekuaitu.kuaitu.widget.MarqueeView;
import com.ekuaitu.kuaitu.widget.MyViewPager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengCallback;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 地图方法说明
 * 1.定位结果：        {@link #onLocationChanged(AMapLocation)}
 * 2.Marker点击回调：  {@link #onMarkerClick(Marker)}
 * 3.单车、汽车切换：   {@link #chooseSwitch(int, boolean)}  无需处理当前的场景，可以直接调用，汽车预约中不能切换
 * 4.路线规划：        RoutePlanUtils.getInstance().startRoutePlanning(...) 地图只能显示单条路线，回调返回距离时间
 * new RoutePlanUtils.startRoutePlanning(...)   地图显示多条路线，不使用单例
 * 5.清空地图         {@link #clearMap()}        如以后在地图上添加其他的内容，需要在此方法中添加清除该内容的代码
 * 6.清除路线         {@link #routePlanningClear()}
 * 7.清除单车和汽车Marker   {@link #clearAllBikeAndCarMarker()}
 */

public class MainActivity extends AppCompatActivity implements AMapLocationListener, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter, MyApplication.OnRemindCarListener {
    private Context mContext = this;
    private MapView mapView;
    private AMap aMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private SensorEventHelper mSensorHelper;
    private MarkerUtils markerUtils;
    public static LatLng curPosition;
    private Marker locationMarker;
    private List<Polygon> coverPolygon = new ArrayList<>();
    private List<Polygon> boundPolygon = new ArrayList<>();   //地图上围栏的集合
    private List<Marker> brandMarkerList = new ArrayList<>(); //商家
    private Circle mCircle;
    private PolylineBoundUtils polylineBoundUtils;
    private ArrayList<Marker> markerList = new ArrayList<>();//地图上单车或者汽车网点的Marker集合
    private ImageView gift_mainActivity;
    private ImageButton imageButton_main_car;
    private ImageButton imageButton_main_bike;
    private LinearLayout switch_mainActivity;
    private ImageView imageView_list;
    private ImageView imageView_hotLine;
    private ImageButton button_search_scan;
    private LinearLayout layout_no_car;
    private TextView tvHaveCarRemindButton, tvLookCarButton;
    private LinearLayout layout_park_detail;
    private LinearLayout layout_place_order;
    private LinearLayout layout_bike_red_detail;
    private TextView red_task_receive;
    private RelativeLayout red_task_red_help;
    private TextView tv_bike_red_lisence;
    private MyViewPager viewPager_parkDetail;
    private RadioGroup radioGroup;
    private RadioButton[] arrRadioButton = null;
    private ParkDetailPagerAdapter adapter;
    private TextView textView_rent;
    private TextView tv_distance_park;
    private TextView tv_address_park;
    private TextView tv_address_no_car;
    private TextView tv_distance_no_car;
    private TextView tx_place_order_timer;
    private TextView tx_place_order_remind1;
    private TextView tx_place_order_remind2;
    private TextView tx_place_order_brand;
    private TextView tx_place_order_plate;
    private ImageView imageView_locate;
    private TextView tv_place_order_position;
    private ImageView iv_order_car;
    private ImageView imageView_help;
    private ImageView imageView_shake;
    private RelativeLayout imageViewShakeLayout;
    private TextView textView_order_cancel;
    private RelativeLayout progressBar_mainActivity;
    private ImageView gift_red_hot;
    private ImageView mes_red_hot;
    private MarqueeView marqueeView;
    private LinearLayout ad_top_main;
    private CityDetailBean.AttachmentBean.EnclosureBean cityInfo;

    private boolean isFirstInMain = true;   //第一次进入主页面
    private boolean isExit = false;
    private boolean isAnimatorShow = false;
    private static Boolean isFirstLocation = true;
    private boolean isTimeOut = false;
    private List<ParkBean.AttachmentBean.ParksBean> parksResult;
    private List<ParkDetailBean.AttachmentBean.CarsBean> totalList = new ArrayList<>();
    private String orderId;
    private String carId;
    private String parkId;
    private String carLicense;
    private int choosePosition = 0;
    private String bikeId;
    private String bikeLicense;
    private int lockType;
    private String pictureId;
    private String bikePrice;
    private CountDownTimer timer;
    private float layoutHeight = 0F;
    private AnimatorSet animSet;
    private PowerManager.WakeLock wakeLock;
    private boolean isLoadingDone = false;
    private int requestCode;
    private static String areaCode;
    private static String adCode;

    private String address;
    private String model = android.os.Build.MODEL;
    private long adLatestTime;
    private View infoWindow = null;

    private RelativeLayout have_car_remind_layout;
    private ImageView ivHaveSet, ivUnSet;
    private String currentRemindParkid;
    private boolean remindCar = false;
    private Map<String, String> notifyMap = new HashMap<>();
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0, false);
        AppManager.getAppManager().addActivity(this);
        mapView = (MapView) findViewById(R.id.map_mainActivity);
        mapView.onCreate(savedInstanceState);
        MyApplication.setOnRemindCarListener(this);
        EventBus.getDefault().register(this);           //注册EventBus
        PushAgent.getInstance(this).enable(new IUmengCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
        initMainView();
        initMainLayout();
        initMap();
        initLocationService();
    }


    private void initMainLayout() {
        initBikeRedLayout();
        initParkDetailLayout();
        initPlaceOrderLayout();
        initNoCarLayout();
    }

    /**
     * 单车，汽车切换
     * 无需处理当前的场景，可以直接调用
     * 汽车预约中不能直接切换单车
     *
     * @param tripMode    1切换至电车，2切换至单车
     * @param isAddMarker 切换后，是否加载地图的单车图标或者汽车网店图标
     */
    private void chooseSwitch(int tripMode, boolean isAddMarker) {
        if (Constants.tripAvai == 3) {
            if (!switch_mainActivity.isShown()) {
                popSwitchButton(true);
            }
        } else {
            if (switch_mainActivity.isShown()) {
                popSwitchButton(false);
            }
        }
        if (tripMode == 1 && (Constants.tripAvai == 3 || Constants.tripAvai == 1)) {
            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 14, 0, 0)), 400, null);
            imageButton_main_car.setBackgroundResource(R.drawable.corner_main_switch_choosed);
            imageButton_main_bike.setBackgroundResource(R.drawable.corner_main_switch_unchoose);
            imageButton_main_car.setImageDrawable(getResources().getDrawable(R.drawable.car_main));
            imageButton_main_bike.setImageDrawable(getResources().getDrawable(R.drawable.bike_main_unchoose));
            layout_bike_red_detail.setVisibility(View.GONE);
            layout_park_detail.setVisibility(View.INVISIBLE);
            layout_place_order.setVisibility(View.GONE);
            layout_no_car.setVisibility(View.GONE);
            imageView_list.setVisibility(View.VISIBLE);
            button_search_scan.setImageDrawable(getResources().getDrawable(R.drawable.search_car_main));
            clearMap();
            initHaveCarRemindView();
            if (boundPolygon.size() != 0) {
                for (int i = 0; i < boundPolygon.size(); i++) {
                    boundPolygon.get(i).remove();
                }
                boundPolygon.clear();
            }
            if (coverPolygon.size() != 0) {
                for (int i = 0; i < coverPolygon.size(); i++) {
                    coverPolygon.get(i).remove();
                }
                coverPolygon.clear();
            }
            if (isAddMarker) {
                getParks();
            }
        } else if (tripMode == 2 && (Constants.tripAvai == 3 || Constants.tripAvai == 2)) {
            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 400, null);
            imageButton_main_bike.setBackgroundResource(R.drawable.corner_main_switch_choosed);
            imageButton_main_car.setBackgroundResource(R.drawable.corner_main_switch_unchoose);
            imageButton_main_bike.setImageDrawable(getResources().getDrawable(R.drawable.bike_main));
            imageButton_main_car.setImageDrawable(getResources().getDrawable(R.drawable.car_main_unchoose));
            layout_bike_red_detail.setVisibility(View.GONE);
            layout_park_detail.setVisibility(View.INVISIBLE);
            layout_place_order.setVisibility(View.GONE);
            layout_no_car.setVisibility(View.GONE);
            imageView_list.setVisibility(View.GONE);
            button_search_scan.setImageDrawable(getResources().getDrawable(R.drawable.scan_qr_main));
            clearMap();
            have_car_remind_layout.setVisibility(View.GONE);
            if (cityInfo != null && cityInfo.getBikeRangeList() != null && boundPolygon.size() == 0) {
                boundPolygon = polylineBoundUtils.addBoundsToMap(cityInfo.getBikeRangeList());
                Log.i("boundPolygon", boundPolygon.size() + "chooseSwitch: ");
            }
            if (isAddMarker) {
                getBikes();
            }
        } else {
            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 14, 0, 0)), 400, null);
        }
    }

    private void initHaveCarRemindView() {
        have_car_remind_layout.setVisibility(View.VISIBLE);
        ivUnSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(MyApplication.getInstance().getUid())) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    return;
                }
                Intent intent = new Intent(MainActivity.this, CarNetSystemActivity.class);
                intent.putExtra(IntentKey.INTENT_LATITUDE, curPosition.latitude + "");
                intent.putExtra(IntentKey.INTENT_LONGITUDE, curPosition.longitude + "");
                intent.putExtra(IntentKey.INTENT_AREACODE, areaCode);
                startActivity(intent);
            }
        });
        ivHaveSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(MyApplication.getInstance().getUid())) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    return;
                }
                Intent intent = new Intent(MainActivity.this, CarNetSystemActivity.class);
                intent.putExtra(IntentKey.INTENT_LATITUDE, curPosition.latitude + "");
                intent.putExtra(IntentKey.INTENT_LONGITUDE, curPosition.longitude + "");
                intent.putExtra(IntentKey.INTENT_AREACODE, areaCode);
                startActivity(intent);
            }
        });
    }


    private void initAppData(final boolean checkUpdate) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).initApp(MyApplication.getInstance().getRequestFieldMap(), model, "1",
                curPosition.longitude + "", curPosition.latitude + "")
                .enqueue(new Callback<InitBean>() {
                    @Override
                    public void onResponse(Call<InitBean> call, final Response<InitBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            InitBean.AttachmentBean attachmentBean = response.body().getAttachment();
                            if (attachmentBean != null && "0".equals(attachmentBean.getIsShowShake())) {
                                imageViewShakeLayout.setVisibility(View.GONE);
                            } else if (attachmentBean != null) {
                                imageViewShakeLayout.setVisibility(View.VISIBLE);
                            }
                            if (response.body().getStatus() == 200) {
                                InitBean.AttachmentBean result = response.body().getAttachment();
                                MyApplication.getInstance().setHotLine(result.getService_call());
                                MyApplication.getInstance().setImageUrl(result.getImgUrl());
                                String versionName = result.getVersionControl().getVersionNum();
                                String forceUpdate = result.getVersionControl().getType() + "";
                                String updateInfo = result.getVersionControl().getUpdateContent();
                                String updateTitle = result.getVersionControl().getUpdateTitle();
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.CAR_DAY_TIME, result.getDayTime());
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.CAR_NIGHT_TIME, result.getNightTime());
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LOTTERY_HISTORY, result.getLotteryHistory());
                                if (isFirstInMain && checkUpdate) {
                                    new VerControlUtils(mContext).update(versionName, forceUpdate, updateInfo, updateTitle);
                                    isFirstInMain = false;
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<InitBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "001");
                    }
                });
    }

    //广告弹框
    private void getAdWindow() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getPopAd(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<AdPopBean>() {
            @Override
            public void onResponse(Call<AdPopBean> call, final Response<AdPopBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().size() != 0) {
                            adLatestTime = response.body().getAttachment().get(0).getStartTime();
                            Log.i("adLast", SharedPreferencesUtils.getInstance(mContext).getLongValue("adLatestTime") + "");
                            if (adLatestTime > SharedPreferencesUtils.getInstance(mContext).getLongValue("adLatestTime")) {
                                gift_red_hot.setVisibility(View.VISIBLE);
                            }
                            if (SharedPreferencesUtils.getInstance(mContext).getIntValue("adPopTime") == 0 || (Calendar.getInstance().get(Calendar.MONTH) + 1) * 100 + Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                                    != SharedPreferencesUtils.getInstance(mContext).getIntValue("adPopTime")) {
                                ArrayList<String> imageList = new ArrayList<>();
                                ArrayList<String> urlList = new ArrayList<>();
                                ArrayList<String> titleList = new ArrayList<>();
                                for (int i = 0; i < response.body().getAttachment().size(); i++) {
                                    imageList.add(response.body().getAttachment().get(i).getImgUrl());
                                    urlList.add(response.body().getAttachment().get(i).getH5Url());
                                    String title = "活动中心";
                                    titleList.add(title);
                                }
                                SharedPreferencesUtils.getInstance(mContext).putIntValue("adPopTime", (Calendar.getInstance().get(Calendar.MONTH) + 1) * 100 + Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                                Intent intent = new Intent(mContext, AdPopActivity.class);
                                intent.putStringArrayListExtra("imageList", imageList);
                                intent.putStringArrayListExtra("urlList", urlList);
                                intent.putStringArrayListExtra("titleList", titleList);
                                intent.putExtra("xLocation", gift_mainActivity.getLeft());
                                intent.putExtra("yLocation", gift_mainActivity.getBottom());
                                startActivity(intent);
                            }
                        }
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<AdPopBean> call, Throwable t) {
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("netError", "003" + t);
            }
        });
    }


    //获取顶部消息及个人中心小红点
    private void getTopAd() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getTopAd(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<AdTopBean>() {
            @Override
            public void onResponse(Call<AdTopBean> call, final Response<AdTopBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200")) {
                        if (response.body().getAttachment() != null) {
                            final List<AdTopBean.AttachmentBean.MessageListBean> messageListBeanList = response.body().getAttachment().getMessageList();
                            //顶部消息
                            if (messageListBeanList == null || messageListBeanList.size() == 0) {
                                ad_top_main.setVisibility(View.GONE);
                                return;
                            } else {
                                ad_top_main.setVisibility(View.VISIBLE);
                            }
                            List adInfo = new ArrayList();
                            List resIds = new ArrayList();
                            for (int i = 0; i < messageListBeanList.size(); i++) {
                                adInfo.add(messageListBeanList.get(i).getContent());
                                if (messageListBeanList.get(i).getMessageType().equals("4")) {
                                    resIds.add(R.drawable.icon_promote);
                                } else if (messageListBeanList.get(i).getMessageType().equals("3")) {
                                    resIds.add(R.drawable.icon_light);
                                } else {
                                    resIds.add(R.drawable.icon_speaker_color);
                                }
                            }
                            marqueeView.startWithList(adInfo, resIds);
                            marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                                @Override
                                public void onItemClick(int position, LinearLayout textView) {
                                    //通知 反馈类型
                                    if (messageListBeanList.get(position).getMessageType().equals("1") || messageListBeanList.get(position).getMessageType().equals("2")) {
                                        Intent intent = new Intent(mContext, MesDetailActivity.class);
                                        intent.putExtra("date", messageListBeanList.get(position).getCreateTime());
                                        intent.putExtra("content", messageListBeanList.get(position).getContent());
                                        startActivity(intent);
                                        //消息已读
                                        readMessage(messageListBeanList.get(position).getId());
                                        //活动类型
                                    } else if (messageListBeanList.get(position).getMessageType().equals("4")) {
                                        Intent intent2 = new Intent(mContext, WebViewActivity.class);
                                        intent2.putExtra(IntentKey.INTENT_WEBVIEW_H5TITLE, true);
                                        intent2.putExtra(IntentKey.INTENT_WEBVIEW_URL, messageListBeanList.get(position).getAdditional()
                                                + "?uid=" + MyApplication.getInstance().getUid()
                                                + "&token=" + MyApplication.getInstance().getToken()
                                                + "&platform=1"
                                                + "&appVersion=" + MyApplication.getInstance().getAppVersion());
                                        startActivity(intent2);
                                        //有车提醒
                                    } else if (messageListBeanList.get(position).getMessageType().equals("3")) {
                                        notifyMap.clear();
                                        notifyMap.put("id", messageListBeanList.get(position).getParkModel().getId());
                                        notifyMap.put("locationName", messageListBeanList.get(position).getParkModel().getLocationName());
                                        notifyMap.put("longitude", messageListBeanList.get(position).getParkModel().getLongitude());
                                        notifyMap.put("latitude", messageListBeanList.get(position).getParkModel().getLatitude());
                                        showHasCarPark(notifyMap);
                                        //消息已读
                                        readMessage(messageListBeanList.get(position).getId());
                                    }
                                }
                            });
                        }
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<AdTopBean> call, Throwable t) {
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("netError", "003" + t);
            }
        });
    }

    //个人中心小红点
    private void getMsgRed() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getMsgRed(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<MsgRedBean>() {
            @Override
            public void onResponse(Call<MsgRedBean> call, final Response<MsgRedBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200")) {
                        if (response.body().getAttachment() != null) {
                            mes_red_hot.setVisibility(response.body().getAttachment().getIsRead().equals("1") ? View.VISIBLE : View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<MsgRedBean> call, Throwable t) {
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("netError", "003" + t);
            }
        });
    }

    //顶部广告已读
    private void readMessage(String messageId) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).readMsg(MyApplication.getInstance().getRequestFieldMap(), messageId).enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                if (MyApplication.getInstance().getUid() != null) {
                    getTopAd();
                }
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
            }
        });
    }

    /**
     * 用户进入app或者重新登录后，检查是否有进行中订单
     *
     * @param firstCheck true:首次进入app查询是否有进行中订单，false:重新登录后查询未完成订单
     */
    private void hasUnFinishOrder(final boolean firstCheck) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUnFinishOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<UnFinishOrderBean>() {
                    @Override
                    public void onResponse(Call<UnFinishOrderBean> call, final Response<UnFinishOrderBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                if (response.body().getAttachment().getIsUnfinished() != 0) {
                                    initAppData(false);
                                    if (response.body().getAttachment().getBusinessType() == 1) {       //电车有进行中订单
                                        Constants.tripMode = 1;
                                        orderId = response.body().getAttachment().getOrderId();
                                        switch (response.body().getAttachment().getStatus()) {
                                            case 0:
                                                chooseSwitch(Constants.tripMode, false);
                                                popSwitchButton(false);
                                                loadCarFindLayout(orderId);
                                                break;
                                            case 10:
                                                isLoadingDone = true;
                                                chooseSwitch(Constants.tripMode, true);
                                                Intent intentInUse = new Intent(mContext, CarInUseActivity.class);
                                                intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, response.body().getAttachment().getOrderId());
                                                intentInUse.putExtra(IntentKey.INTENT_AREACODE, areaCode);
                                                startActivity(intentInUse);
                                                break;
                                            case 15:
                                            case 16:
                                            case 17:
                                                isLoadingDone = true;
                                                chooseSwitch(Constants.tripMode, true);
                                                final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
                                                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                                kuaituDialog.setMessage(getString(R.string.unPayOrder));
                                                kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                                    @Override
                                                    public void onYesClick() {
                                                        IntentUtils.toSettlementActivity(mContext, response.body().getAttachment().getOrderId(), "");
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                                    @Override
                                                    public void onNoClick() {
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setCancelable(false);
                                                kuaituDialog.show();
                                                break;
                                        }
                                    } else {    //单车有进行中订单
                                        Constants.tripMode = 2;
                                        orderId = response.body().getAttachment().getOrderId();
                                        bikeId = response.body().getAttachment().getOrderModel().getBikeModel().getBikeId();
                                        bikeLicense = response.body().getAttachment().getOrderModel().getBikeModel().getLicenseTag();
                                        lockType = response.body().getAttachment().getOrderModel().getBikeModel().getLockType();
                                        pictureId = response.body().getAttachment().getOrderModel().getBikeModel().getPicture();
                                        bikePrice = response.body().getAttachment().getOrderModel().getBikeModel().getPrice();
                                        isLoadingDone = true;
                                        switch (response.body().getAttachment().getStatus()) {
                                            case 0:
                                                //3.1.0版本取消了单车预约，防止产生预约订单的产生，主动把预约的订单取消掉
                                                cancelOrder();
                                                //没有单车进行中订单，把用户上次是否已经关锁重置
                                                SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                                                break;
                                            case 10:
                                                chooseSwitch(Constants.tripMode, true);
                                                Intent intent;
                                                if (response.body().getAttachment().getIsRedPackage() == 0) { //0 普通单车   1任务车
                                                    intent = new Intent(mContext, BikeInUseRedActivity.class);
                                                } else {
                                                    intent = new Intent(mContext, BikeInUseRedActivity.class);
                                                }
                                                intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                                intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
                                                intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
                                                startActivity(intent);
                                                break;
                                            case 15:
                                                //没有单车进行中订单，把用户上次是否已经关锁重置
                                                SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                                                chooseSwitch(Constants.tripMode, true);
                                                final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
                                                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                                kuaituDialog.setMessage(getString(R.string.unPayOrder));
                                                kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                                    @Override
                                                    public void onYesClick() {
                                                        IntentUtils.toSettlementActivity(MainActivity.this, response.body().getAttachment().getOrderId(),
                                                                response.body().getAttachment().getOrderModel().getBikeModel().getBikeId());
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                                    @Override
                                                    public void onNoClick() {
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setCancelable(false);
                                                kuaituDialog.show();
                                                break;
                                        }
                                    }
                                } else {  //没有进行中订单
                                    //没有单车进行中订单，把用户上次是否已经关锁重置
                                    SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                                    isLoadingDone = true;
                                    if (firstCheck) {
                                        getAdWindow();
                                        initAppData(true);
                                        initGreenLeave();
                                        getTripMode();
                                        if (Constants.tripMode == 1) {
                                            chooseSwitch(1, true);
                                        } else if (Constants.tripMode == 2) {
                                            chooseSwitch(2, true);
                                        } else {
                                            switch_mainActivity.setVisibility(View.GONE);
                                        }
                                    } else {
                                        initAppData(false);
                                    }
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<UnFinishOrderBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "012" + t);
                    }
                });
    }

    /**
     * 当用户点租车时，检查用户是否有进行中订单，若没有订单，检查用户资格
     *
     * @param type 检查用户资格正常后 ，type:1非任务车跳转扫码租车  2任务车跳转扫码租车
     */
    private void hasUnpayOrder(final int type) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUnFinishOrder(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<UnFinishOrderBean>() {
            @Override
            public void onResponse(Call<UnFinishOrderBean> call, final Response<UnFinishOrderBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        if (response.body().getAttachment().getIsUnfinished() != 0) {
                            if (response.body().getAttachment().getBusinessType() == 1) {//电车未完成订单
                                orderId = response.body().getAttachment().getOrderId();
                                switch (response.body().getAttachment().getStatus()) {
                                    case 0:
                                        chooseSwitch(Constants.tripMode, false);
                                        popSwitchButton(false);
                                        loadCarFindLayout(orderId);
                                        break;
                                    case 10:
                                        isLoadingDone = true;
                                        chooseSwitch(Constants.tripMode, true);
                                        Intent intentInUse = new Intent(mContext, CarInUseActivity.class);
                                        intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, response.body().getAttachment().getOrderId());
                                        intentInUse.putExtra(IntentKey.INTENT_AREACODE, areaCode);
                                        startActivity(intentInUse);
                                        break;
                                    case 15:
                                    case 16:
                                    case 17:
                                        isLoadingDone = true;
                                        chooseSwitch(Constants.tripMode, true);
                                        final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
                                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                        kuaituDialog.setMessage(getString(R.string.unPayOrder));
                                        kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesClick() {
                                                IntentUtils.toSettlementActivity(mContext, response.body().getAttachment().getOrderId(), "");
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                            @Override
                                            public void onNoClick() {
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setCancelable(false);
                                        kuaituDialog.show();
                                        break;
                                }
                            } else {    //单车未完成订单
                                Constants.tripMode = 2;
                                orderId = response.body().getAttachment().getOrderId();
                                bikeId = response.body().getAttachment().getOrderModel().getBikeModel().getBikeId();
                                bikeLicense = response.body().getAttachment().getOrderModel().getBikeModel().getLicenseTag();
                                lockType = response.body().getAttachment().getOrderModel().getBikeModel().getLockType();
                                pictureId = response.body().getAttachment().getOrderModel().getBikeModel().getPicture();
                                bikePrice = response.body().getAttachment().getOrderModel().getBikeModel().getPrice();
                                isLoadingDone = true;
                                switch (response.body().getAttachment().getStatus()) {
                                    case 0:
                                        //3.1.0版本取消了单车预约，防止产生预约订单的产生，主动把预约的订单取消掉
                                        //没有单车进行中订单，把用户上次是否已经关锁重置
                                        SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                                        cancelOrder();
                                        break;
                                    case 10:
                                        chooseSwitch(Constants.tripMode, true);
                                        Intent intent;
                                        if (response.body().getAttachment().getIsRedPackage() == 0) { //0 普通单车   1任务车
                                            intent = new Intent(mContext, BikeInUseRedActivity.class);
                                        } else {
                                            intent = new Intent(mContext, BikeInUseRedActivity.class);
                                        }
                                        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                        intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
                                        intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
                                        startActivity(intent);
                                        break;
                                    case 15:
                                        //没有单车进行中订单，把用户上次是否已经关锁重置
                                        SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                                        final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
                                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                        kuaituDialog.setMessage(getString(R.string.unPayOrder));
                                        kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesClick() {
                                                IntentUtils.toSettlementActivity(MainActivity.this, response.body().getAttachment().getOrderId(),
                                                        response.body().getAttachment().getOrderModel().getBikeModel().getBikeId());
                                                kuaituDialog.dismiss();
                                                chooseSwitch(Constants.tripMode, true);
                                                setAnimator(imageView_locate, -260, 0f, 300L, false);
                                                setAnimator(imageView_hotLine, -260, 0f, 300L, false);
                                            }
                                        });
                                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                            @Override
                                            public void onNoClick() {
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setCancelable(false);
                                        kuaituDialog.show();
                                        break;
                                }
                            }
                        } else {
                            //没有单车进行中订单，把用户上次是否已经关锁重置
                            SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                            isLoadingDone = true;
                            certifyBikePlaceOrder(type);
                        }
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<UnFinishOrderBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                Log.i("netError", "013" + t);
            }
        });
    }


    //验证用户汽车认证状态
    private void checkUserStatus() {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).confirmCertify(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<ConfirmCertifyBean>() {
            @Override
            public void onResponse(Call<ConfirmCertifyBean> call, Response<ConfirmCertifyBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar_mainActivity.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.IDENTITY_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LICENSE_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEPOSIT_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        Intent intent = new Intent(mContext, CarCertificateActivity.class);
                        switch (response.body().getAttachment().getDepositStatus()) {
                            //保证金
                            case 0:
                                intent.putExtra("SubmitFlag", 3);
                                startActivity(intent);
                                break;
                            case 1:
                                switch (response.body().getAttachment().getIdentityStatus()) {
                                    //身份信息未审核
                                    //身份信息失败
                                    case 10:
                                    case 12:
                                        intent.putExtra("SubmitFlag", 1);
                                        startActivity(intent);
                                        break;
                                    //身份信息审核中
                                    //身份信息审核成功
                                    case 11:
                                    case 13:
                                        switch (response.body().getAttachment().getLicenseStatus()) {
                                            case 10:    //证照未审核
                                            case 12:    //证照失败
                                                intent.putExtra("SubmitFlag", 2);
                                                startActivity(intent);
                                                break;
                                            case 11:    //证照审核中
                                                ToastCompat.makeText(mContext, "您的资格正在审核中...", Toast.LENGTH_SHORT).show();
                                            case 13:    //证照审核成功
                                                break;
                                        }
                                        break;
                                }
                                break;
                        }
                    } else {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<ConfirmCertifyBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void cancelOrder() {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).cancelBikeOrder(MyApplication.getInstance().getRequestFieldMap(), orderId)
                .enqueue(new Callback<CancelOrder>() {
                    @Override
                    public void onResponse(Call<CancelOrder> call, Response<CancelOrder> response) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        if (response.isSuccessful() && response.body() != null) {
                        }
                    }

                    @Override
                    public void onFailure(Call<CancelOrder> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.findBikeFailure), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                });
    }


    private void initMainView() {
        imageView_help = (ImageView) findViewById(R.id.imageView_help);
        gift_mainActivity = (ImageView) findViewById(R.id.gift_mainActivity);
        progressBar_mainActivity = (RelativeLayout) findViewById(R.id.progressBar_mainActivity);
        imageView_locate = (ImageView) findViewById(R.id.imageView_locate);
        imageView_list = (ImageView) findViewById(R.id.imageView_list);
        imageView_shake = (ImageView) findViewById(R.id.imageView_shake);
        imageViewShakeLayout = (RelativeLayout) findViewById(R.id.imageView_shake_layout);
        imageView_hotLine = (ImageView) findViewById(R.id.imageView_hotline);
        button_search_scan = (ImageButton) findViewById(R.id.button_search_scan);
        switch_mainActivity = (LinearLayout) findViewById(R.id.switch_mainActivity);
        imageButton_main_car = (ImageButton) findViewById(R.id.imageButton_main_car);
        imageButton_main_bike = (ImageButton) findViewById(R.id.imageButton_main_bike);
        gift_red_hot = (ImageView) findViewById(R.id.gift_red_hot);
        mes_red_hot = (ImageView) findViewById(R.id.mes_red_hot);
        have_car_remind_layout = (RelativeLayout) findViewById(R.id.have_car_remind_layout);
        ivHaveSet = (ImageView) findViewById(R.id.have_car_remind_setted);
        ivUnSet = (ImageView) findViewById(R.id.have_car_remind_unset);
        ad_top_main = (LinearLayout) findViewById(R.id.ad_top_main);
        marqueeView = (MarqueeView) findViewById(R.id.ad_top_info_main);
        //单车切换按钮
        imageButton_main_bike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(MainActivity.this, Constants.SELECT_TYPE_BIKE);
                if (Constants.tripMode == 1 || Constants.tripMode == -1) {
                    chooseSwitch(2, true);
                    Constants.tripMode = 2;
                } else {
                    ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //电车切换按钮
        imageButton_main_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(MainActivity.this, Constants.SELECT_TYPE_CAR);
                if (Constants.tripMode == 2 || Constants.tripMode == -1) {
                    chooseSwitch(1, true);
                    Constants.tripMode = 1;
                }
            }
        });

        //弹窗消失后礼物按钮的动画
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(gift_mainActivity, "rotation", 0, 30, 0, -30, 0);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(gift_mainActivity, "translationX", 0, 5, 0, -5, 0);
        animSet = new AnimatorSet();
        animSet.setDuration(250);
        animSet.setInterpolator(new LinearInterpolator());
        animSet.playTogether(anim1, anim2);

        //摇一摇动画
        shakeHandler.sendEmptyMessageDelayed(START_ANIMATION, 3000);
    }


    private final int STOP_ANIMATION = 0;
    private final int START_ANIMATION = 1;
    Handler shakeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case START_ANIMATION:
                    Animation operatingAnim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.shake);
                    AccelerateInterpolator interpolator = new AccelerateInterpolator();
                    operatingAnim.setInterpolator(interpolator);
                    imageView_shake.startAnimation(operatingAnim);
                    shakeHandler.sendEmptyMessageDelayed(STOP_ANIMATION, 3000);
                    break;
                case STOP_ANIMATION:
                    imageView_shake.clearAnimation();
                    shakeHandler.sendEmptyMessageDelayed(START_ANIMATION, 3000);
                    break;
            }

        }
    };


    //初始化网点车辆弹出布局,从列表选择，搜索附近，点击图标公用该布局

    private void initParkDetailLayout() {
        layout_park_detail = (LinearLayout) findViewById(R.id.layout_park_detail);
        tv_distance_park = (TextView) findViewById(R.id.tv_distance_park);
        tv_address_park = (TextView) findViewById(R.id.tv_address_park);
        viewPager_parkDetail = (MyViewPager) findViewById(R.id.viewPager_parkDetail);
        adapter = new ParkDetailPagerAdapter(mContext, totalList);
        viewPager_parkDetail.setAdapter(adapter);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup_viewPager);
        textView_rent = (TextView) findViewById(R.id.textView_rent);
        viewPager_parkDetail.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                arrRadioButton[position].setChecked(true);
                choosePosition = position;      //设置viewpager当前选择的position
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        //立即租用按钮监听
        textView_rent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(MainActivity.this, Constants.IMMEDIATE_HIRE_CAR);
                Intent intent = new Intent();
                if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {
                    intent.setClass(mContext, ConfirmRentCarActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("carsBean", adapter.getItem(choosePosition));
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constants.REQUEST_RENT);
                } else {
                    intent.setClass(mContext, HelpActivity.class);
                    intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                    startActivity(intent);
                    overridePendingTransition(R.anim.top_down, 0);
                }
            }
        });
    }

    //初始化viewPager指示器
    private void initViewPagerDots(int count) {
        if (count == 1) {
            count = 0;
        }
        radioGroup.removeAllViews();
        arrRadioButton = null;
        arrRadioButton = new RadioButton[count];
        for (int i = 0; i < count; i++) {
            RadioButton radioButton = new RadioButton(mContext);
            radioButton.setPadding(15, 0, 15, 0);
            radioButton.setButtonDrawable(R.drawable.dots);
            radioGroup.addView(radioButton);
            arrRadioButton[i] = radioButton;
        }
        if (arrRadioButton.length != 0) {
            arrRadioButton[0].setChecked(true);
        }
    }

    //初始化下单寻车弹出布局
    private void initPlaceOrderLayout() {
        layout_place_order = (LinearLayout) findViewById(R.id.layout_place_order);
        iv_order_car = (ImageView) findViewById(R.id.iv_order_car);
        LinearLayout imageButton_order_find_car = (LinearLayout) findViewById(R.id.imageButton_order_find_car);
        tv_place_order_position = (TextView) findViewById(R.id.tv_place_order_position);
        tx_place_order_brand = (TextView) findViewById(R.id.tx_place_order_brand);
        textView_order_cancel = (TextView) findViewById(R.id.textView_order_cancel);
        tx_place_order_plate = (TextView) findViewById(R.id.tx_place_order_plate);
        tx_place_order_timer = (TextView) findViewById(R.id.tx_place_order_timer);
        tx_place_order_remind1 = (TextView) findViewById(R.id.tx_place_order_remind1);
        tx_place_order_remind2 = (TextView) findViewById(R.id.tx_place_order_remind2);
        LinearLayout getImageButton_order_lock_on = (LinearLayout) findViewById(R.id.imageButton_order_lock_on);
        imageButton_order_find_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!AccountStatus.isLogin(mContext)) {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.loginFirst), Toast.LENGTH_SHORT).show();
                    Intent intent1 = new Intent();
                    intent1.setClass(mContext, LoginActivity.class);
                    startActivity(intent1);
                } else {
                    findCar(orderId, carId, curPosition.longitude + "", curPosition.latitude + "");
                }
            }
        });
        getImageButton_order_lock_on.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage(getString(R.string.openCarRemind));
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                        if (!AccountStatus.isLogin(mContext)) {
                            ToastCompat.makeText(mContext, getResources().getString(R.string.loginFirst), Toast.LENGTH_SHORT).show();
                            Intent intent1 = new Intent();
                            intent1.setClass(mContext, LoginActivity.class);
                            startActivity(intent1);
                            kuaituDialog.dismiss();
                        } else {
                            kuaituDialog.dismiss();
                            openCarDoor(orderId, carId, curPosition.longitude + "", curPosition.latitude + "");
                        }

                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.show();
            }
        });
        textView_order_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final boolean isCancel3count = false;
                String reminderTitle = !isCancel3count ? "每天可取消3次，超出3次则当日无法用车，确定取消订单么？" : "您已取消3次订单，今日无法再使用车辆";
                final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage(reminderTitle);
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        if (!isCancel3count) {
                            showCancelComfirmDialog();
                        }
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.show();
            }
        });
    }

    /**
     * 取消订单确认对话框
     */
    private void showCancelComfirmDialog() {
        String reminderTitle = isTimeOut ? getString(R.string.cancelOrderPay) : getString(R.string.cancelOrder);
        final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
        kuaituDialog.setTitle(getString(R.string.dialogTitle));
        kuaituDialog.setMessage(reminderTitle);
        kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                if (!AccountStatus.isLogin(mContext)) {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.loginFirst), Toast.LENGTH_SHORT).show();
                    Intent intent1 = new Intent();
                    intent1.setClass(mContext, LoginActivity.class);
                    startActivity(intent1);
                } else {
                    cancelCarOrder(orderId);
                }
                kuaituDialog.dismiss();
            }
        });
        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                kuaituDialog.dismiss();
            }
        });
        kuaituDialog.show();
    }

    //初始化无车辆弹出布局
    private void initNoCarLayout() {
        layout_no_car = (LinearLayout) findViewById(R.id.layout_no_car);
        tvHaveCarRemindButton = (TextView) findViewById(R.id.havecar_remind_button);
        tvLookCarButton = (TextView) findViewById(R.id.havecar_looksystem_button);
        tv_address_no_car = (TextView) findViewById(R.id.tv_address_no_car);
        tv_distance_no_car = (TextView) findViewById(R.id.tv_distance_no_car);

        tvHaveCarRemindButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("已设置提醒".equals(tvHaveCarRemindButton.getText().toString())) {
                    return;
                }
                if (TextUtils.isEmpty(MyApplication.getInstance().getUid())) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    return;
                }
                final SetRemindTimeDialog dialog = new SetRemindTimeDialog(MainActivity.this);
                dialog.setYesOnclickListener("确定", new SetRemindTimeDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        if (TextUtils.isEmpty(dialog.getSelectRadioButton())) {
                            ToastCompat.makeText(MainActivity.this, "请选择一个有效时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        requestSaveRemind(currentRemindParkid, Integer.parseInt(dialog.getSelectRadioButton()));
                        dialog.dismiss();
                    }
                });
                dialog.setNoOnclickListener("取消", new SetRemindTimeDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });

        tvLookCarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(MainActivity.this, Constants.NEAR_CAR);
                Intent intent = new Intent();
                intent.setClass(mContext, CarListActivity.class);
                intent.putExtra(IntentKey.INTENT_LATITUDE, curPosition.latitude + "");
                intent.putExtra(IntentKey.INTENT_LONGITUDE, curPosition.longitude + "");
                startActivityForResult(intent, Constants.REQUEST_CARLIST);
            }
        });
    }

    /**
     * 设置有车提醒按钮是否可点击
     *
     * @param clickable
     */
    private void setRemindButtonClickable(boolean clickable) {
        if (clickable) {
            tvHaveCarRemindButton.setText("有车提醒");
            tvHaveCarRemindButton.setBackgroundResource(R.drawable.selector_button_bg_yellow);
            tvHaveCarRemindButton.setTextColor(getResources().getColor(R.color.white));
            ((ImageView) findViewById(R.id.nocar_image)).setImageResource(R.drawable.not_havecar_cry);
            String message = "很抱歉，该网点暂时没有车辆，设置有车提醒，有车将提醒您!";
            SpannableString spannableString = new SpannableString(message);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary));
            spannableString.setSpan(colorSpan, message.indexOf("有车提醒"), message.indexOf("有车提醒") + 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ((TextView) findViewById(R.id.nocar_text)).setText(spannableString);
        } else {
            tvHaveCarRemindButton.setText("已设置提醒");
            tvHaveCarRemindButton.setBackgroundResource(R.drawable.corner_background_gray);
            tvHaveCarRemindButton.setTextColor(getResources().getColor(R.color.gray3));
            ((ImageView) findViewById(R.id.nocar_image)).setImageResource(R.drawable.image_mascot);
            ((TextView) findViewById(R.id.nocar_text)).setText("您已设置有车提醒，请耐心等待");
        }
    }

    /**
     * 更新设置有车提醒的提示图标
     *
     * @param haveSet
     */
    private void updateRemindStatusView(boolean haveSet) {
        ivUnSet.setVisibility(haveSet ? View.GONE : View.VISIBLE);
        ivHaveSet.setVisibility(haveSet ? View.VISIBLE : View.GONE);
    }

    /**
     * 设置提醒
     *
     * @param parkIdStr    网点id
     * @param remindMinute 有车提醒有效时间（分钟）
     */
    private void requestSaveRemind(String parkIdStr, int remindMinute) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).saveRemind(MyApplication.getInstance().getRequestFieldMap(), parkIdStr, remindMinute, 0).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                progressBar_mainActivity.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        setRemindButtonClickable(false);
                        updateRemindStatusView(true);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
            }
        });
    }

    //初始花任务单车详情
    private void initBikeRedLayout() {
        layout_bike_red_detail = (LinearLayout) findViewById(R.id.layout_bike_red_detail);
        red_task_red_help = (RelativeLayout) findViewById(R.id.red_task_red_help);
        tv_bike_red_lisence = (TextView) findViewById(R.id.red_detail_lisence);
        red_task_receive = (TextView) findViewById(R.id.red_task_receive);
    }


    private void intentScan(int requestCode) {
        Intent intent = new Intent(mContext, ScanBikeQrActivity.class);
        if (requestCode == Constants.REQUEST_SCAN_RED) {
            intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
            intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
            intent.putExtra(IntentKey.INTENT_BIKE_LICENSE_DESIGNATED, bikeLicense);
            intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
            intent.putExtra("isRedBike", 1);
        }
        intent.putExtra("requestCode", requestCode);
        startActivity(intent);
    }


    //一键获取附近车辆,弹出网点详情布局
    public void getNearCar(final LatLng curPosition) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getNearCar(MyApplication.getInstance().getRequestFieldMap(), curPosition.longitude + "", curPosition.latitude + "").enqueue(new Callback<NearCarBean>() {
            @Override
            public void onResponse(Call<NearCarBean> call, Response<NearCarBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        NearCarBean.AttachmentBean.ParksBean result = response.body().getAttachment().getParks();
                        if (result.getCarModelList() != null && result.getCarModelList().size() != 0) {
                            popSwitchButton(false);
                            //返回最近网点的数据，适配为ParkDetail的Bean，然后获取该网点的第一辆车
                            List<ParkDetailBean.AttachmentBean.CarsBean> list = new ArrayList<>();
                            for (int i = 0; i < result.getCarModelList().size(); i++) {
                                ParkDetailBean.AttachmentBean.CarsBean carsBean = new ParkDetailBean.AttachmentBean.CarsBean();
                                NearCarBean.AttachmentBean.ParksBean.CarModelListBean resultIndex = result.getCarModelList().get(i);
                                carsBean.setBrand(resultIndex.getBrand());
                                carsBean.setModel(resultIndex.getModel());
                                carsBean.setLicenseTag(resultIndex.getLicenseTag());
                                carsBean.setMileage(resultIndex.getMileage());
                                carsBean.setId(resultIndex.getId());
                                carsBean.setParkId(resultIndex.getParkId());
                                carsBean.setSeat(resultIndex.getSeat());
                                carsBean.setPicture(resultIndex.getPicture());
                                carsBean.setAbatement(resultIndex.getAbatement());
                                carsBean.setCompanyByRisk(resultIndex.getCompanyByRisk());
                                carsBean.setParkName(resultIndex.getParkName());
                                carsBean.setLatitude(resultIndex.getLatitude());
                                carsBean.setLongitude(resultIndex.getLongitude());
                                ParkDetailBean.AttachmentBean.CarsBean.ValuationRuleModelBean vrBean = new ParkDetailBean.AttachmentBean.CarsBean.ValuationRuleModelBean();
                                vrBean.setWeekDayPrice(resultIndex.getValuationRuleModel().getWeekDayPrice());
                                vrBean.setWeekNightPrice(resultIndex.getValuationRuleModel().getWeekNightPrice());
                                carsBean.setValuationRuleModel(vrBean);
                                list.add(carsBean);
                            }
                            //弹出网点详情布局
                            layout_no_car.setVisibility(View.GONE);
                            layout_place_order.setVisibility(View.GONE);
                            layout_place_order.setVisibility(View.GONE);
                            adapter = new ParkDetailPagerAdapter(mContext, list);
                            viewPager_parkDetail.setAdapter(adapter);
                            initViewPagerDots(result.getCarModelList().size());
                            popCarLayout(layout_park_detail, true);
                            choosePosition = 0;
                            initViewPagerDots(result.getCarModelList().size());
                            if (result.getLocationName() != null) {
                                tv_address_park.setText(result.getLocationName());
                            } else {
                                tv_address_park.setText("暂无位置信息");
                            }

                            RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition,
                                    new LatLng(result.getLatitude(), result.getLongitude()), true,
                                    new RoutePlanUtils.OnRoutePlannedListener() {
                                        @Override
                                        public void onRoutePlannedListener(int distance, int duration) {
                                            DecimalFormat df = new DecimalFormat("0.00");
                                            tv_distance_park.setText(df.format(distance / 1000.0) + "千米");
                                        }
                                    });

                        } else {
                            Intent intent = new Intent();
                            intent.setClass(mContext, CarListActivity.class);
                            intent.putExtra(IntentKey.INTENT_LATITUDE, curPosition.latitude + "");
                            intent.putExtra(IntentKey.INTENT_LONGITUDE, curPosition.longitude + "");
                            startActivityForResult(intent, Constants.REQUEST_CARLIST);
                        }
                    } else {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<NearCarBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                Log.i("netError", "014" + t);
            }
        });
    }


    public void clickView(View view) {
        final Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.button_search_scan:        //一键最近车辆 或扫码取车
                if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {  //登录状态
                    if (curPosition != null) {
                        if (Constants.tripMode == 1) {            //电车
                            getNearCar(curPosition);
                            MobclickAgent.onEvent(MainActivity.this, Constants.ONEKEY_SELECTCAR_CAR);
                        } else {                                //单车,检查用户资格
                            hasUnpayOrder(1);
                            MobclickAgent.onEvent(MainActivity.this, Constants.SCANCODE_FOR_BIKE);
                        }
                    } else {
                        ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    intent.setClass(mContext, HelpActivity.class);
                    intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                    startActivity(intent);
                    overridePendingTransition(R.anim.top_down, 0);
                }
                break;
            case R.id.imageView_locate:          //定位
                MobclickAgent.onEvent(this, Constants.POSITION_BIKE);
                if (curPosition != null) {
                    if (Constants.tripMode == 1) {
                        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 14, 0, 0)), 400, null);
                    } else {
                        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 400, null);
                    }
                } else {
                    ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.imageView_refresh:          //刷新
                MobclickAgent.onEvent(this, Constants.REFRESH_BIKE);
                clearMap();
                if (!switch_mainActivity.isShown()) {
                    popSwitchButton(true);
                }
                if (curPosition != null) {
                    aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 400, null);
                }
                if (Constants.tripMode == 1) {
                    getParks();
                } else if (Constants.tripMode == 2) {
                    if (curPosition != null) {
                        getBikes();
                    } else {
                        ToastCompat.makeText(mContext, "正在定位...", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.imageView_list:           //列表
                intent.setClass(mContext, CarListActivity.class);
                intent.putExtra(IntentKey.INTENT_LATITUDE, curPosition.latitude + "");
                intent.putExtra(IntentKey.INTENT_LONGITUDE, curPosition.longitude + "");
                startActivityForResult(intent, Constants.REQUEST_CARLIST);
                MobclickAgent.onEvent(MainActivity.this, Constants.NEAR_CAR);
                break;
            case R.id.imageView_shake:
                intent.setClass(mContext, ShakeActivity.class);
                intent.putExtra(IntentKey.INTENT_LATITUDE, curPosition.latitude + "");
                intent.putExtra(IntentKey.INTENT_LONGITUDE, curPosition.longitude + "");
                intent.putExtra(IntentKey.INTENT_AREACODE, areaCode);
                intent.putExtra(IntentKey.INTENT_ADDRESS, address);
                startActivity(intent);
                break;
            case R.id.imageView_hotline:  //客服
                if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {
                    MobclickAgent.onEvent(MainActivity.this, Constants.FEEDBACK);
                    intent.setClass(mContext, ComplaintsActivity.class);
                    if (layout_place_order.isShown()) {
                        if (orderId != null) {
                            intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        }
                        if (Constants.tripMode == 1) {
                            intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                            intent.putExtra("licenseTag", carLicense);
                        } else if (Constants.tripMode == 2) {
                            intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                            intent.putExtra("licenseTag", bikeLicense);
                        }
                    } else {
                        intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                    }
                    startActivity(intent);
                    MobclickAgent.onEvent(MainActivity.this, Constants.HOME_CUSTOMER_SERVICE);
                } else {
                    intent.setClass(mContext, HelpActivity.class);
                    intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                    startActivity(intent);
                    overridePendingTransition(R.anim.top_down, 0);
                }
                break;
            case R.id.myInfo_mainActivity:      //个人中心
                if (isLoadingDone && !isFirstLocation) {
                    if (layout_place_order == null || !layout_place_order.isShown()) {
                        intent.setClass(mContext, PersonalCenterActivity.class);
                        startActivity(intent);
                    }
                } else {
                    clearMap();
                    isFirstLocation = true;
                    mLocationClient.startLocation();
                    progressBar_mainActivity.setVisibility(View.VISIBLE);
                }
                MobclickAgent.onEvent(this, Constants.USERCENTER);
                break;
            case R.id.gift_mainActivity: { // 活动
                MobclickAgent.onEvent(MainActivity.this, Constants.ACTIVITY_CENTER);
                gift_red_hot.setVisibility(View.GONE);
                SharedPreferencesUtils.getInstance(mContext).putLongValue("adLatestTime", adLatestTime);
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.GIFT_URL + "?citycode=" + areaCode);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "活动中心");
                startActivity(intent);
            }
            break;
            case R.id.imageView_help: //使用帮助 小绿叶
                MobclickAgent.onEvent(MainActivity.this, Constants.HELP_UNLOGIN);
                ObjectAnimator animator = ObjectAnimator.ofFloat(imageView_help, "translationY", DensityUtils.dp2px(mContext, 174), DensityUtils.dp2px(mContext, 0));
                animator.setDuration(600).setInterpolator(new AccelerateInterpolator());
                animator.start();
                intent.setClass(mContext, HelpActivity.class);
                intent.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                startActivity(intent);
                break;
        }
    }


    /*地图相关的方法*/

    public void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(false);
            aMap.setMapType(AMap.MAP_TYPE_NAVI);

            //设置点击marker事件监听器
            aMap.setOnMarkerClickListener(this);
            aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
            UiSettings uiSettings = aMap.getUiSettings();
            //设置地图交互
            uiSettings.setMyLocationButtonEnabled(false);
            uiSettings.setScaleControlsEnabled(true);
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setZoomControlsEnabled(false);
            uiSettings.setScrollGesturesEnabled(true);
            uiSettings.setZoomGesturesEnabled(true);
            uiSettings.setTiltGesturesEnabled(false);

            //设置定位的参数
            if (mLocationClient == null) {
                mLocationClient = new AMapLocationClient(getApplicationContext());
                mLocationOption = new AMapLocationClientOption();
                //设置定位监听
                mLocationClient.setLocationListener(this);
                //设置为高精度定位模式
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                mLocationOption.setInterval(2000);
                mLocationOption.setMockEnable(true);
                //设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
                progressBar_mainActivity.setVisibility(View.VISIBLE);
            }
            markerUtils = new MarkerUtils(mContext, aMap);
            polylineBoundUtils = new PolylineBoundUtils(aMap);
            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    backPress(false);
                }
            });


            aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {

                }

                @Override
                public void onCameraChangeFinish(CameraPosition cameraPosition) {
                    if (Constants.tripMode == 2) {
                        if (cityInfo != null) {
                            if (cameraPosition.zoom < 14.5 && coverPolygon.size() == 0) {
                                Log.i("cameraPosition", cameraPosition.zoom + "");
                                coverPolygon = polylineBoundUtils.addCoversToMap(cityInfo.getBikeRangeList());
                            } else if (cameraPosition.zoom >= 14.5 && coverPolygon.size() != 0) {
                                Log.i("cameraPosition", cameraPosition.zoom + "   " + coverPolygon.size() + "");
                                for (int i = 0; i < coverPolygon.size(); i++) {
                                    coverPolygon.get(i).remove();
                                }
                                coverPolygon.clear();
                            }
                        }
                    }
                }
            });
        }
    }

    private void getRedBikeHotSpotInfo(final Marker redMarker) {

        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getRedBikeHotSpotInfo(MyApplication.getInstance().getRequestFieldMap(), redMarker.getPosition().latitude + "", redMarker.getPosition().longitude + "").enqueue(new Callback<RedBikeHotSpotInfoBean>() {
            @Override
            public void onResponse(Call<RedBikeHotSpotInfoBean> call, Response<RedBikeHotSpotInfoBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        //绘制任务车的地图UI
                        drawRedBikeMap(response.body().getAttachment());
                    } else {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<RedBikeHotSpotInfoBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                Log.i("netError", "020" + t);
            }
        });

    }

    private void drawRedBikeMap(final List<RedBikeHotSpotInfoBean.AttachmentBean> rebBikeInfo) {
        //缩放地图
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (curPosition != null) {
            b.include(curPosition);
        }
        //画热区和商家
        for (int i = 0; i < rebBikeInfo.size(); i++) {
            b.include(new LatLng(rebBikeInfo.get(i).getCenterLatitude(), rebBikeInfo.get(i).getCenterLongitude()));
            List<LatLng> redBikeBound = new ArrayList<>();
            for (RedBikeHotSpotInfoBean.AttachmentBean.PointListBean redBikeBoundInfo : rebBikeInfo.get(i).getPointList()) {
                redBikeBound.add(new LatLng(redBikeBoundInfo.getLatitude(), redBikeBoundInfo.getLongitude()));
            }
            boundPolygon.add(polylineBoundUtils.addBoundAndCoverToMap(redBikeBound));
            if ((rebBikeInfo.get(i).getBusinessName() != null && !rebBikeInfo.get(i).getBusinessName().equals(""))) {
                new MarkerUtils(mContext, aMap).addBrandMarkerToMap(rebBikeInfo.get(i).getBusinessLatitude(), rebBikeInfo.get(i).getBusinessLongitude(),
                        rebBikeInfo.get(i).getBusinessName(), rebBikeInfo.get(i).getBusinessImg(), new MarkerUtils.OnBrandMarkerAddedListener() {
                            @Override
                            public void onBrandMarkerAdded(Marker marker) {
                                //商家Marker，加入到list中，后续用来从地图上清除这些marker
                                brandMarkerList.add(marker);
                            }
                        });
            }
        }
        aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(
                b.build(),
                DensityUtils.dp2px(mContext, 100), DensityUtils.dp2px(mContext, 100), DensityUtils.dp2px(mContext, 100), DensityUtils.dp2px(mContext, 300)),
                400,
                null);
    }


    //ClickMarker的点击事件
    @Override
    public boolean onMarkerClick(final Marker marker) {
        //最好不在此方法重置orderId，bikeId，carId，pictureId全局属性
        final Map<String, String> markerInfo = (Map<String, String>) marker.getObject();

//电车
        if (Constants.tripMode == 1 && aMap != null && marker != locationMarker && !layout_place_order.isShown()) {
            MobclickAgent.onEvent(MainActivity.this, Constants.SELECT_CARANDBIKE_CAR);
            //根据parkId,弹出网点详情
            loadParkDetailLayout(markerInfo.get("parkId"), markerInfo.get("parkName"), marker.getPosition());

//单车
        } else if (Constants.tripMode == 2 && aMap != null && marker != locationMarker)

            //任务单车详情布局未展示,所有的图标都可以点击
            if (!layout_bike_red_detail.isShown()) {
                MobclickAgent.onEvent(MainActivity.this, Constants.SELECT_CARANDBIKE_BIKE);

                popSwitchButton(false);
                //清空地图上已有的路线规划
                routePlanningClear();
//任务
                if (markerInfo.get("isRedBike").equals("1")) {
                    //任务单车详情弹出
                    loadBikeRedDetailLayout(marker.getPosition(), markerInfo.get("bikePrice"), markerInfo.get("bikeId"), markerInfo.get("bikeLicense"), Integer.parseInt(markerInfo.get("lockType")));
                    //任务单车地图UI
                    getRedBikeHotSpotInfo(marker);
                } else {
//普通单车
                    //普通单车地图UI
                    progressBar_mainActivity.setVisibility(View.VISIBLE);
                    RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition, marker.getPosition(), true,
                            new RoutePlanUtils.OnRoutePlannedListener() {
                                @Override
                                public void onRoutePlannedListener(int distance, int duration) {
                                    progressBar_mainActivity.setVisibility(View.GONE);
                                    marker.setTitle(distance + "");
                                    marker.setSnippet(markerInfo.get("bikeLicense"));
                                    marker.showInfoWindow();
                                }
                            });
                }


            } else {
                //任务单车布局已经展示，只有任务车路线规划指示标可点击，弹出气泡
                if (markerInfo.get("redRouteNum") != null && !markerInfo.get("redRouteNum").equals("")) {
                    marker.showInfoWindow();
                }
            }
        return true;
    }


    private void routePlanningClear() {
        //清除普通车路线规划
        RoutePlanUtils.getInstance().clearRoute();

        //清除商家图标
        if (brandMarkerList != null && brandMarkerList.size() != 0) {
            for (Marker marker : brandMarkerList) {
                marker.remove();
            }
            brandMarkerList.clear();
        }
        for (Marker marker : markerList) {
            marker.hideInfoWindow();
        }
    }


    //清除地图所有图标
    private void clearAllBikeAndCarMarker() {
        if (markerList != null) {
            for (Marker marker : markerList) {
                marker.hideInfoWindow();
                marker.remove();
            }
        }
    }

    private void clearMap() {
        clearAllBikeAndCarMarker();  //清除地图上的Marker
        routePlanningClear();  //清除地图上的路线规划
    }

    //点击Marker,显示InfoWindow的回调
    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(mContext).inflate(R.layout.info_window, null);
        }
        render(marker, infoWindow); //设置弹窗的内容
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }


    public void render(Marker marker, View view) {
        TextView tv_distance = (TextView) view.findViewById(R.id.info_window_distance);
        TextView tv_license = (TextView) view.findViewById(R.id.info_window_license);
        tv_distance.setText(marker.getTitle());
        tv_license.setText(marker.getSnippet());
    }


    private void startLocation() {
        mLocationClient.startLocation();
    }


    private boolean isFirstLocationError = true;

    /**
     * 每次定位后回调方法，（使用的连续定位模式，按照间隔自动定位）
     *
     * @param amapLocation
     */
    @Override
    public void onLocationChanged(final AMapLocation amapLocation) {
        if (amapLocation == null) {
            new AlertDialog.Builder(mContext).setTitle("小兔提示").setMessage("启动定位似乎出现了异常，请您退出应用重试。")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            AppManager.getAppManager().AppExit(mContext);
                        }
                    }).setCancelable(false).show();
            return;
        }

        int locationErrorCode = amapLocation.getErrorCode();
        if (locationErrorCode == 0) {//定位成功
            curPosition = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());// 更新定位
            address = amapLocation.getAddress();
            Constants.cityName = amapLocation.getCity();
            if (isFirstLocation) {//首次成功的定位
                progressBar_mainActivity.setVisibility(View.GONE);
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 14, 0, 0)));
                if (locationMarker != null) {
                    locationMarker.remove();
                }
                locationMarker = markerUtils.addLocationIcon(curPosition);
                //mCircle = polylineBoundUtils.addCircle(curPosition, amapLocation.getAccuracy());//添加定位精度圆
                locationMarker.setClickable(false);
                mSensorHelper.setCurrentMarker(locationMarker);//设置陀螺仪
                if (amapLocation.getCityCode() != null && !amapLocation.getCityCode().equals("")) {
                    areaCode = amapLocation.getCityCode();//高德区号
                    adCode = amapLocation.getAdCode();//高德县区级编码
                    MyApplication.getInstance().setAreaCode(areaCode);
                    getCityInfo();//获取城市信息
                }
                findRemindStatus();
                isFirstLocation = false;
            } else {   //非首次成功的定位
                locationMarker.setPosition(curPosition);
                //mCircle.setCenter(curPosition);
                //mCircle.setRadius(amapLocation.getAccuracy());
            }

        } else {//定位失败
            if (isFirstLocationError) {  //第一次定位失败执行，之后的失败定位不再执行
                isFirstLocationError = false;
                if (locationErrorCode == 13 || locationErrorCode == 6 || locationErrorCode == 18 || locationErrorCode == 19) {   //关闭了系统定位服务
                    new AlertDialog.Builder(mContext).setTitle(getString(R.string.dialogTitle)).setMessage(getString(R.string.LocationServiceRemind))
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivityForResult(intent, Constants.REQUEST_Location_Service);
                                }
                            }).setCancelable(false).show();
                } else if (locationErrorCode == 12) {  //缺少定位权限
                    new AlertDialog.Builder(mContext).setTitle("小兔提示").setMessage("您拒绝了某些权限，部分功能将无法使用，请您到设置中开启权限。")
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    startActivity(intent);
                                }
                            }).setCancelable(false).show();
                } else if (locationErrorCode == 4) {
                    new AlertDialog.Builder(mContext).setTitle("小兔提示").setMessage("定位失败，您的网络似乎不太畅通。")
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                    startActivity(intent);
                                }
                            }).setCancelable(false).show();
                } else if (locationErrorCode == 9) {
                    new AlertDialog.Builder(mContext).setTitle("小兔提示").setMessage("启动定位似乎出现了异常，请您退出重试。")
                            .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AppManager.getAppManager().AppExit(mContext);
                                }
                            }).setCancelable(false).show();
                } else {
                    new AlertDialog.Builder(mContext).setTitle("小兔提示").setMessage("获取位置信息失败，您的网络似乎不太畅通。")
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                    startActivity(intent);
                                }
                            }).setCancelable(false).show();
                }
            }
        }

    }

    //根据该城市可用的出行方式，以及用户上次使用的方式，获得一种出行方式
    private void getTripMode() {
        if (Constants.tripAvai == 3) {
            int userTripMode = SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.USER_TRIP_METHOD);
            if (userTripMode == 0 || userTripMode == 2) {
                Constants.tripMode = 2;
            } else {
                Constants.tripMode = 1;
            }
        } else if (Constants.tripAvai == 1) {
            Constants.tripMode = 1;
        } else if (Constants.tripAvai == 2) {
            Constants.tripMode = 2;
        } else if (Constants.tripAvai == 0) {
            Constants.tripMode = -1;
            button_search_scan.setVisibility(View.GONE);
            final KuaituDialog kuaituDialog = new KuaituDialog(MainActivity.this);
            kuaituDialog.setTitle(getString(R.string.dialogTitle));
            kuaituDialog.setMessage(getString(R.string.noOpenCity));
            kuaituDialog.setYesOnclickListener("确认", new KuaituDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.show();
        }
    }

    //获取城市信息
    public void getCityInfo() {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getCityInfo(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CityDetailBean>() {
                    @Override
                    public void onResponse(Call<CityDetailBean> call, Response<CityDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getAttachment() != null) {
                            progressBar_mainActivity.setVisibility(View.GONE);
                            if (response.body().getStatus() == 400) {
                                Constants.tripAvai = 0;  //该城市可用的出行方式
                            } else if (response.body().getStatus() == 200) {
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.DEPOSIT_BIKE, response.body().getAttachment().getEnclosure().getBikeBail());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.DEPOSIT_CAR, response.body().getAttachment().getEnclosure().getCarBail());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN, response.body().getAttachment().getEnclosure().getAliPay());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_WXPAY_OPEN, response.body().getAttachment().getEnclosure().getWechatPay());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_SHARE_INVITE, response.body().getAttachment().getEnclosure().getActUserShare());
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.IS_CAR_PREPARE, response.body().getAttachment().getEnclosure().getActCarPrepare());
                                cityInfo = response.body().getAttachment().getEnclosure();
                                if (cityInfo.getIsCar() == 1 && cityInfo.getIsBike() == 1) {
                                    Constants.tripAvai = 3; //全可用
                                } else if (cityInfo.getIsCar() == 1 && cityInfo.getIsBike() == 0) {
                                    Constants.tripAvai = 1;  //汽车可用
                                } else if (cityInfo.getIsCar() == 0 && cityInfo.getIsBike() == 1) {
                                    Constants.tripAvai = 2;//单车可用
                                } else if (cityInfo.getIsCar() == 0 && cityInfo.getIsBike() == 0) {
                                    Constants.tripAvai = 0;//全不可用
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {  //是否登录
                                hasUnFinishOrder(true);      //检查未完成订单
                            } else {  //未登录
                                isLoadingDone = true;
                                getAdWindow();
                                initAppData(true);
                                initGreenLeave();
                                getTripMode();
                                if (Constants.tripMode == 1) {
                                    chooseSwitch(1, true);
                                } else if (Constants.tripMode == 2) {
                                    chooseSwitch(2, true);
                                } else {
                                    switch_mainActivity.setVisibility(View.GONE);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CityDetailBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "002");
                    }
                });
    }

    //获取全部网点图标
    public void getParks() {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getParks(MyApplication.getInstance().getRequestFieldMap(), "1", "3000")
                .enqueue(new Callback<ParkBean>() {
                    @Override
                    public void onResponse(Call<ParkBean> call, Response<ParkBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                //  imageView_refresh.setVisibility(View.GONE);
                                clearAllBikeAndCarMarker();
                                parksResult = response.body().getAttachment().getParks();
                                //添加网点标记
                                if (parksResult.size() != 0) {
                                    markerList = markerUtils.addCarMarkersToMap(aMap, parksResult);
                                }
                                if (remindCar && notifyMap != null) {
                                    remindCar = false;
                                    //根据parkId,弹出有车的网点详情
                                    loadParkDetailLayout(notifyMap.get("id"), notifyMap.get("locationName"),
                                            new LatLng(Double.parseDouble(notifyMap.get("latitude")), Double.parseDouble(notifyMap.get("longitude"))));
                                }
                            } else {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ParkBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "015" + t);
                    }
                });
    }

    //网点详情
    public void loadParkDetailLayout(String parkId, final String parkName, final LatLng parkPosition) {
        currentRemindParkid = parkId;
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        tv_address_park.setText(parkName);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getParkDetail(MyApplication.getInstance().getRequestFieldMap(), parkId)
                .enqueue(new Callback<ParkDetailBean>() {
                    @Override
                    public void onResponse(Call<ParkDetailBean> call, Response<ParkDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                ParkDetailBean.AttachmentBean attachmentBean = response.body().getAttachment();
                                List<ParkDetailBean.AttachmentBean.CarsBean> list = attachmentBean.getCars();
                                if (list.size() != 0) {             //有可租车辆，刷新pagerAdapter
                                    adapter = new ParkDetailPagerAdapter(mContext, list);
                                    viewPager_parkDetail.setAdapter(adapter);
                                    initViewPagerDots(list.size());
                                    choosePosition = 0;
                                    if (!layout_park_detail.isShown()) {
                                        popSwitchButton(false);       //隐藏切换按钮
                                        layout_no_car.setVisibility(View.GONE);
                                        layout_place_order.setVisibility(View.GONE);
                                        popCarLayout(layout_park_detail, true);
                                    }

                                } else {
                                    if (!layout_no_car.isShown()) {
                                        popSwitchButton(false);
                                        layout_park_detail.setVisibility(View.INVISIBLE);
                                        layout_place_order.setVisibility(View.GONE);
                                        tv_address_no_car.setText(" ");
                                        popCarLayout(layout_no_car, true);
                                    }
                                    if (attachmentBean.getRemindStatus() == 0) {//无提醒
                                        setRemindButtonClickable(true);
                                    } else {//有提醒
                                        setRemindButtonClickable(false);
                                    }
                                    tv_address_no_car.setText(parkName);
                                }

                                RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition, parkPosition, true,
                                        new RoutePlanUtils.OnRoutePlannedListener() {
                                            @Override
                                            public void onRoutePlannedListener(int distance, int duration) {
                                                progressBar_mainActivity.setVisibility(View.GONE);
                                                DecimalFormat df = new DecimalFormat("0.00");
                                                tv_distance_no_car.setText(df.format(distance / 1000.0) + "千米");
                                                tv_distance_park.setText(df.format(distance / 1000.0) + "千米");
                                            }
                                        });


                            } else {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ParkDetailBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "016" + t);
                    }
                });
    }

    /**
     * 查询当前用户是否有车提醒
     */
    private void findRemindStatus() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getRemind(MyApplication.getInstance().getRequestFieldMap(), curPosition.latitude + "", curPosition.longitude + "", "1", "1").enqueue(new Callback<GetRemindBean>() {
            @Override
            public void onResponse(Call<GetRemindBean> call, Response<GetRemindBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        GetRemindBean.Attachment attachment = response.body().getAttachment();
                        if (attachment != null) {
                            List<GetRemindBean.Attachment.RemindPark> recordedBeanList = attachment.getParkList();
                            int remindStatus = attachment.getRemindStatus();
                            if (remindStatus == 0) {
                                updateRemindStatusView(false);
                            } else {
                                updateRemindStatusView(true);
                            }
                        }
                    } else {
                        ToastCompat.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<GetRemindBean> call, Throwable t) {

        Log.i("dfd","df");
            }
        });
    }

    //寻电车中订单
    private void loadCarFindLayout(String orderId) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getOrderDetail(MyApplication.getInstance().getRequestFieldMap(), orderId)
                .enqueue(new Callback<OrderDetailBean>() {
                    @Override
                    public void onResponse(Call<OrderDetailBean> call, Response<OrderDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                isLoadingDone = true;
                                progressBar_mainActivity.setVisibility(View.GONE);
                                OrderDetailBean.AttachmentBean result = response.body().getAttachment();
                                carId = response.body().getAttachment().getCarId() + "";
                                clearMap();
                                markerList.add(markerUtils.addCarMarkerToMap(result.getCarModel().getLatitude(), result.getCarModel().getLongitude()));
                                RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition,
                                        new LatLng(result.getCarModel().getLatitude(), result.getCarModel().getLongitude()), true, null);

                                GeocodeSearchViewUtils geocodeSearchViewUtils = new GeocodeSearchViewUtils();
                                geocodeSearchViewUtils.startGeocodeSearch(mContext, result.getCarModel().getLatitude(), result.getCarModel().getLongitude(), tv_place_order_position);
                                Date date = new Date();
                                reLoadCarFindLayout(result.getCarModel().getPicture(),
                                        result.getCarModel().getBrand() + result.getCarModel().getModel(),
                                        result.getCarModel().getLicenseTag(), 30 * 60 * 1000 - (date.getTime() - result.getOrderTime()));
                            } else {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<OrderDetailBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "017" + t);
                    }
                });
    }


    //寻车
    public void findCar(String orderId, String carId, String longitude, String latitude) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).findCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude).enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                    } else {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.findCarFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * app重启电车寻车中
     *
     * @param placeOrderTimer 下单倒计时
     */
    private void reLoadCarFindLayout(String pictureId, String carBrand, String carLicense, long placeOrderTimer) {
        layout_park_detail.setVisibility(View.INVISIBLE);
        popSwitchButton(false);
        popCarLayout(layout_place_order, true);
        tx_place_order_brand.setText(carBrand);
        tx_place_order_plate.setText(carLicense);
        popCarLayout(layout_place_order, true);
        this.carLicense = carLicense;
        ImageLoader.getInstance().displayImage(mContext, MyApplication.getInstance().getImageUrl() + pictureId, iv_order_car);
        findCarTimer(placeOrderTimer);
    }

    //寻车倒计时
    private void findCarTimer(final long placeOrderTimer) {
        timer = new CountDownTimer(placeOrderTimer, 1000) {
            @Override
            public void onTick(long l) {
                if (l >= 900000) { //15min
                    tx_place_order_remind1.setText("预约中，");
                    tx_place_order_timer.setText(TimeUtils.formatSecond(l / 1000 - 900 + ""));
                    tx_place_order_remind2.setText("后开始计费");
                } else {
                    tx_place_order_remind1.setText("已开始计费，");
                    tx_place_order_timer.setText(TimeUtils.formatSecond(l / 1000 + ""));
                    tx_place_order_remind2.setText("后自动取消订单");
                }
            }

            @Override
            public void onFinish() {
                checkCarOrderStatus();
            }
        };
        timer.start();
        acquireWakeLock();
    }

    //倒计时结束时，从服务器查询订单状态(订单是否真正超时)
    private void checkCarOrderStatus() {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).checkAutoCancel(MyApplication.getInstance().getRequestFieldMap(), orderId).enqueue(new Callback<CheckCarOrderBean>() {
            @Override
            public void onResponse(Call<CheckCarOrderBean> call, final Response<CheckCarOrderBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        if (response.body().getAttachment().getOrderStatus() == 17) {
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                            final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                            kuaituDialog.setTitle(getString(R.string.dialogTitle));
                            kuaituDialog.setMessage(getString(R.string.orderCancel));
                            kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    IntentUtils.toSettlementActivity(mContext, response.body().getAttachment().getOrderId(), "");
                                    kuaituDialog.dismiss();
                                }
                            });
                            kuaituDialog.setNoOnclickListener("暂不支付", new KuaituDialog.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    kuaituDialog.dismiss();
                                    clearMap();
                                    getParks();
                                    popCarLayout(layout_place_order, false);
                                    //显示切换开关
                                    popSwitchButton(true);
                                }
                            });
                            kuaituDialog.setCancelable(false);
                            kuaituDialog.show();
                        } else if (response.body().getAttachment().getOrderStatus() == 0) {
                            timer.cancel();
                            Date date = new Date();
                            findCarTimer(30 * 60 * 1000 - (date.getTime() - response.body().getAttachment().getOrderTime()));
                        }
                    } else {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<CheckCarOrderBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.findCarFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //开车门
    public void openCarDoor(final String orderId, final String carId, String longitude, String latitude) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);

        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).openCarDoor(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude, "0").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        Intent intent = new Intent(mContext, CarInUseActivity.class);
                        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        intent.putExtra("carId", carId);
                        intent.putExtra("parkId", parkId);
                        intent.putExtra(IntentKey.INTENT_AREACODE, areaCode);
                        //停止计时器
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                        }
                        progressBar_mainActivity.setVisibility(View.GONE);
                        //下单寻车布局消失
                        layout_place_order.setVisibility(View.GONE);
                        setAnimator(layout_park_detail, 0f, 200f, 300L, false);
                        startActivity(intent);
                    } else {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.openCarDoorFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //取消电车订单
    public void cancelCarOrder(final String orderId) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).cancelCarOrder(MyApplication.getInstance().getRequestFieldMap(), orderId).enqueue(new Callback<CancelOrder>() {
            @Override
            public void onResponse(Call<CancelOrder> call, Response<CancelOrder> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar_mainActivity.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getOrders().getStatus() == 102) {
                            ToastCompat.makeText(mContext, getResources().getString(R.string.cancelOrderSuccess), Toast.LENGTH_SHORT).show();
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                            clearMap();
                            getParks();
                            popCarLayout(layout_place_order, false);
                            //显示切换开关
                            popSwitchButton(true);
                        } else if (response.body().getAttachment().getOrders().getStatus() == 16 || response.body().getAttachment().getOrders().getStatus() == 17) {
                            timer.cancel();
                            timer = null;
                            releaseWakeLock();
                            IntentUtils.toSettlementActivity(mContext, orderId, "");
                        }
                        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 400, null);
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar_mainActivity.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CancelOrder> call, Throwable t) {
                progressBar_mainActivity.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.cancelOrderFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //单车详情布局
    private void loadBikeRedDetailLayout(LatLng bikePosition, String bikePrice, final String bikeId, String bikeLicense, int lockType) {
        if (layout_bike_red_detail != null && !layout_bike_red_detail.isShown()) {
            popSwitchButton(false);
            popBikeLayout(layout_bike_red_detail, true);
        }
        //初始换全局bikeId
        this.bikeId = bikeId;
        this.bikeLicense = bikeLicense;
        this.lockType = lockType;
        tv_bike_red_lisence.setText(bikeLicense);
        // 任务单车 接受任务
        red_task_receive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(MainActivity.this, Constants.IMMEDIATE_HIRE_BIKE);
                if (!AccountStatus.isLogin(mContext)) {
                    Intent intent1 = new Intent();
                    intent1.setClass(mContext, HelpActivity.class);
                    intent1.putExtra(IntentKey.INTENT_TRIP_MODE, Constants.tripMode);
                    startActivity(intent1);
                } else {
                    hasUnpayOrder(2);
                }
            }
        });

        red_task_red_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "任务攻略");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.REDPACKAGE_DETAIL);
                startActivity(intent);
            }
        });

    }


    /**
     * @param view
     * @param isAppear 单车的布局显示 隐藏
     */
    private void popBikeLayout(View view, boolean isAppear) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        layoutHeight = DensityUtils.px2dp(mContext, view.getMeasuredHeight());
        if (isAppear) {
            if (view != layout_bike_red_detail) {
                setAnimator(imageView_locate, 0f, -(layoutHeight - 5), 300L, true);
                setAnimator(imageView_hotLine, 0f, -(layoutHeight - 5), 300L, true);
            }
            setAnimator(view, layoutHeight + 13, 0f, 300L, true);
            view.setVisibility(View.VISIBLE);
            Log.i("layoutHeightBike", layoutHeight + "");
        } else {
            if (view != layout_bike_red_detail) {
                setAnimator(imageView_locate, -(layoutHeight - 5), 0f, 300L, false);
                setAnimator(imageView_hotLine, -(layoutHeight - 5), 0f, 300L, false);
            }
            setAnimator(view, 0f, layoutHeight + 15, 300L, false);
        }
    }

    /**
     * @param view
     * @param isAppear 电车的布局显示 隐藏
     */
    private void popCarLayout(View view, boolean isAppear) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        layoutHeight = DensityUtils.px2dp(mContext, view.getMeasuredHeight());

        Log.i("layoutHeightCar", layoutHeight + "");
        if (view == layout_no_car || view == layout_place_order) {
            if (isAppear) {
                setAnimator(view, layoutHeight, 0f, 300L, true);
                setAnimator(imageView_locate, 0f, -(layoutHeight), 300L, true);
                setAnimator(imageView_hotLine, 0f, -(layoutHeight), 300L, true);
            } else {
                setAnimator(imageView_locate, -(layoutHeight), 0f, 300L, false);
                setAnimator(imageView_hotLine, -(layoutHeight), 0f, 300L, false);
                setAnimator(view, 0f, layoutHeight, 300L, false);
            }
        } else {    //4.4.2的系统，测量的高度与其他版本不同（不知原因）
            if (android.os.Build.VERSION.SDK_INT == 19) {
                layoutHeight += DensityUtils.dp2px(mContext, 15);
            }
            if (isAppear) {
                setAnimator(view, layoutHeight - 50, 0f, 300L, true);
                setAnimator(imageView_locate, 0f, -(layoutHeight - 50), 300L, true);
                setAnimator(imageView_hotLine, 0f, -(layoutHeight - 50), 300L, true);
            } else {
                setAnimator(imageView_locate, -(layoutHeight - 50), 0f, 300L, false);
                setAnimator(imageView_hotLine, -(layoutHeight - 50), 0f, 300L, false);
                setAnimator(view, 0f, layoutHeight - 50, 300L, false);
            }
        }
    }


    //获取自行车图标
    public void getBikes() {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getBikes(MyApplication.getInstance().getRequestFieldMap(), curPosition.longitude + "", curPosition.latitude + "")
                .enqueue(new Callback<BikeAroundBean>() {
                    @Override
                    public void onResponse(Call<BikeAroundBean> call, Response<BikeAroundBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                // imageView_refresh.setVisibility(View.GONE);
                                progressBar_mainActivity.setVisibility(View.VISIBLE);
                                clearAllBikeAndCarMarker();
                                List<BikeAroundBean.AttachmentBean.BikesBean> bikesResult;
                                if (response.body().getAttachment().getBikes().size() > 100) {
                                    bikesResult = response.body().getAttachment().getBikes().subList(0, 99);
                                } else {
                                    bikesResult = response.body().getAttachment().getBikes();
                                }

                                //添加网点标记
                                if (bikesResult.size() != 0) {
                                    progressBar_mainActivity.setVisibility(View.VISIBLE);
                                    markerList = markerUtils.addBikeMarkersToMap(aMap, bikesResult);
                                    progressBar_mainActivity.setVisibility(View.GONE);
                                }
                            } else if (response.body().getStatus() == 400) {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                /*ToastCompat toast = ToastCompat.makeText(mContext, "附近没有可用单车", Toast.LENGTH_LONG);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();*/
                            } else {
                                progressBar_mainActivity.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<BikeAroundBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "018" + t);
                    }
                });
    }


    //弹窗动画消失后后回调
    @Subscribe
    public void AnimalEvent(AnimalEvent event) {
        if (event.finish) {
            animSet.start();
        }
    }

    //扫码开锁后回调，清除主页面
    @Subscribe
    public void onScanSussEvent(ScanSussEvent event) {
        if (event.isScanSuss) {
            timer.cancel();
            timer = null;
            releaseWakeLock();
            //隐藏单车寻车布局
            backPress(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //从列表返回
        if (requestCode == Constants.REQUEST_CARLIST && resultCode == Constants.RESULT_CARLIST) {
            Bundle bundle = data.getExtras();
            List<ParkDetailBean.AttachmentBean.CarsBean> list = new ArrayList<>();
            ParkDetailBean.AttachmentBean.CarsBean carsBean = new ParkDetailBean.AttachmentBean.CarsBean();
            carsBean.setBrand(bundle.getString("carBrand"));
            carsBean.setModel(bundle.getString("carModel"));
            carsBean.setLicenseTag(bundle.getString("carLicense"));
            carsBean.setMileage(bundle.getInt("carDuration"));
            carsBean.setId(bundle.getString("carId"));
            carsBean.setSeat(bundle.getInt("seats"));
            carsBean.setPicture(bundle.getString("picture"));
            carsBean.setParkId(bundle.getString("parkId"));
            carsBean.setCompanyByRisk(bundle.getDouble("passengerRisk"));
            carsBean.setAbatement(bundle.getDouble("sdew"));
            carsBean.setParkName(bundle.getString("parkName"));
            carsBean.setLatitude(bundle.getDouble("latitude"));
            carsBean.setLongitude(bundle.getDouble("longitude"));
            ParkDetailBean.AttachmentBean.CarsBean.ValuationRuleModelBean vrBean = new ParkDetailBean.AttachmentBean.CarsBean.ValuationRuleModelBean();
            vrBean.setWeekDayPrice(Integer.parseInt(bundle.getString("dayPrice")));
            vrBean.setWeekNightPrice(Integer.parseInt(bundle.getString("nightPrice")));
            carsBean.setValuationRuleModel(vrBean);
            list.add(carsBean);
            layout_no_car.setVisibility(View.GONE);
            layout_place_order.setVisibility(View.GONE);
            adapter = new ParkDetailPagerAdapter(mContext, list);
            viewPager_parkDetail.setAdapter(adapter);
            initViewPagerDots(0);
            popCarLayout(layout_park_detail, true);
            choosePosition = 0;
            popSwitchButton(false);
            tv_address_park.setText(bundle.getString("areaName"));
            RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition,
                    new LatLng(bundle.getDouble("latitude"), bundle.getDouble("longitude")), true,
                    new RoutePlanUtils.OnRoutePlannedListener() {
                        @Override
                        public void onRoutePlannedListener(int distance, int duration) {
                            progressBar_mainActivity.setVisibility(View.GONE);
                            DecimalFormat df = new DecimalFormat("0.00");
                            tv_distance_no_car.setText(df.format(distance / 1000.0) + "千米");
                            tv_distance_park.setText(df.format(distance / 1000.0) + "千米");
                        }
                    });

        }
        //确认租用电车页面返回
        else if (requestCode == Constants.REQUEST_RENT && resultCode == Constants.RESULT_RENT) {
            String carBrand = data.getStringExtra("carBrand");
            String carPlate = data.getStringExtra("carPlate");
            orderId = data.getStringExtra(IntentKey.INTENT_ORDER_ID);
            carId = data.getStringExtra("carId");
            parkId = data.getStringExtra("parkId");
            String pictureId = data.getStringExtra("picture");
            String carLatitude = data.getStringExtra("carLatitude");
            String carLongitude = data.getStringExtra("carLongitude");
            clearMap();
            markerList.add(markerUtils.addCarMarkerToMap(Double.parseDouble(carLatitude), Double.parseDouble(carLongitude)));
            GeocodeSearchViewUtils geocodeSearchViewUtils = new GeocodeSearchViewUtils();
            geocodeSearchViewUtils.startGeocodeSearch(mContext, Double.parseDouble(carLatitude), Double.parseDouble(carLongitude), tv_place_order_position);
            RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition, new LatLng(Double.parseDouble(carLatitude), Double.parseDouble(carLongitude)),
                    true, null);
            reLoadCarFindLayout(pictureId, carBrand, carPlate, 30 * 60 * 1000);
            //开启定位服务返回结果
        } else if (requestCode == Constants.REQUEST_Location_Service) {
            initLocationService();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Constants.tripMode != -1) {
            button_search_scan.setVisibility(View.VISIBLE);
        }
        if ((curPosition != null && !TextUtils.isEmpty(areaCode)) || Constants.isCancelRemind || Constants.isSaveRemind) {
            Constants.isCancelRemind = false;
            Constants.isSaveRemind = false;
            findRemindStatus();
        }
        mapView.onResume();
        if (!isFirstLocation) {
            mLocationClient.startLocation();
        }
        //刷新地图图标
        if (!isFirstInMain && curPosition != null && !layout_bike_red_detail.isShown() && !layout_place_order.isShown()
                && !layout_park_detail.isShown() && !layout_no_car.isShown()) {
            if (Constants.tripMode == 1) {
                getParks();
            } else if (Constants.tripMode == 2) {
                getBikes();
            }
        }
        initSensor();
        if (MyApplication.getInstance().getUid() != null) {
            getTopAd();
            getMsgRed();
        }

        if (Constants.SHAKE_ACTIVITY_IS_END) {
            Constants.SHAKE_ACTIVITY_IS_END = false;
            imageViewShakeLayout.setVisibility(View.GONE);
        }

        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }


    //初始化方向传感器
    private void initSensor() {
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        } else {
            mSensorHelper = new SensorEventHelper(this);
            mSensorHelper.registerSensorListener();
            if (mSensorHelper.getCurrentMarker() == null && locationMarker != null) {
                mSensorHelper.setCurrentMarker(locationMarker);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Constants.tripMode != -1 && SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) == null) {
            button_search_scan.setVisibility(View.GONE);
        }
        mLocationClient.stopLocation();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mapView.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
        finish();
    }

    /**
     * @param isShow 隐藏/显示切换按钮
     */
    private void popSwitchButton(Boolean isShow) {
        if (Constants.tripAvai == 3) {
            int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            switch_mainActivity.measure(w, h);
            if (isShow) {
                setAnimator(switch_mainActivity, -43, 0f, 300L, true);
            } else {
                setAnimator(switch_mainActivity, 0f, -43, 300L, false);
            }
        }
    }

    /**
     * @param view     控件
     * @param isAppear 出现或消失
     */
    private void setAnimator(final View view, float start, float end, long duration, boolean isAppear) {
        ObjectAnimator animator;
        animator = ObjectAnimator.ofFloat(view, "translationY", DensityUtils.dp2px(mContext, start), DensityUtils.dp2px(mContext, end));
        animator.setDuration(duration);
        if (isAppear) {
            view.setVisibility(View.VISIBLE);
        } else {
            switch (Constants.tripMode) {
                case 1:
                    if (view == switch_mainActivity || view == layout_park_detail || view == layout_no_car || view == layout_place_order) {
                        animator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animator) {
                                isAnimatorShow = true;
                            }

                            @Override
                            public void onAnimationEnd(Animator animator) {
                                isAnimatorShow = false;
                                if (view == switch_mainActivity) {
                                    switch_mainActivity.setVisibility(View.GONE);
                                } else {
                                    layout_park_detail.setVisibility(View.INVISIBLE);
                                    layout_no_car.setVisibility(View.GONE);
                                    layout_place_order.setVisibility(View.GONE);
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animator) {
                            }

                            @Override
                            public void onAnimationRepeat(Animator animator) {
                            }
                        });
                    }
                    break;
                case 2:
                    if (view == switch_mainActivity || view == layout_bike_red_detail) {
                        animator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animator) {
                                isAnimatorShow = true;
                            }

                            @Override
                            public void onAnimationEnd(Animator animator) {
                                isAnimatorShow = false;
                                if (view == switch_mainActivity) {
                                    switch_mainActivity.setVisibility(View.GONE);
                                } else {
                                    layout_bike_red_detail.setVisibility(View.GONE);
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animator) {
                            }

                            @Override
                            public void onAnimationRepeat(Animator animator) {
                            }
                        });
                    }
                    break;
            }
        }
        animator.start();
    }

    //返回键弹出布局消失，按两次退出应用
    @Override
    public void onBackPressed() {
        backPress(true);
    }

    private void backPress(boolean isExit) {
        switch (Constants.tripMode) {
            case 1: //电车
                if (!isAnimatorShow && (layout_no_car.isShown() || layout_park_detail.isShown())) {
                    if (layout_no_car.isShown()) {
                        popCarLayout(layout_no_car, false);
                        popSwitchButton(true);
                        routePlanningClear();
                        if (curPosition != null) {
                            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 14, 0, 0)), 400, null);
                        }
                        return;
                    } else if (layout_park_detail.isShown()) {
                        popCarLayout(layout_park_detail, false);
                        popSwitchButton(true);
                        routePlanningClear();
                        if (curPosition != null) {
                            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 14, 0, 0)), 400, null);
                        }
                        return;
                    }
                }
                if (isExit) {
                    exit();
                }
                break;
            case 2:  //单车
                if (!isAnimatorShow && RoutePlanUtils.getInstance().isRouteOnMap() || layout_bike_red_detail.isShown()) {  //任务车存在路线规划或者普通车存在路线规划
                    popBikeLayout(layout_bike_red_detail, false); //隐藏任务布局
                    popSwitchButton(true);                                    //顶部title出现
                    routePlanningClear();
                    if (curPosition != null) {
                        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 400, null);
                    }
                } else {
                    if (isExit) {
                        exit();
                    }
                }
                break;
            case -1:
                if (isExit) {
                    exit();
                }
                break;
        }
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastCompat.makeText(this, "再按一次退出快兔出行", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            if (timer != null) {
                timer.cancel();
                timer = null;
                releaseWakeLock();
            }
            if (coverPolygon.size() != 0) {
                for (int i = 0; i < coverPolygon.size(); i++) {
                    coverPolygon.get(i).remove();
                }
                coverPolygon.clear();
            }
            AppManager.getAppManager().AppExit(mContext);
            Constants.tripMode = -1;
        }
    }

    /**
     * isContinue
     * 不传或者为false：保持离开MainActivity时的状态;
     * true: MainActivity页面的内容重置，此时如果isLogin为true,检查未完成订单，initApp();
     * <p>
     * <p>
     * chooseCar
     * 不传或者为false: 不执行动作
     * true: WebView中点击"我要用车"跳转来，切换至汽车，跳出资格认证流程
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra("isContinue", false)) {            //继续跳转之前的步骤

        } else if (intent.getBooleanExtra("remindCar", false)) {  //点击有车提醒通知跳转而来
            notifyMap.clear();
            notifyMap = (Map<String, String>) intent.getSerializableExtra("notifyMap");
            readMessage(notifyMap.get("id"));
            showHasCarPark(notifyMap);
        } else if (intent.getBooleanExtra("chooseCar", false)) {  //WebView"我要用车"跳转来
            if (Constants.tripMode == 2 && (Constants.tripAvai == 3 || Constants.tripAvai == 1)) {
                chooseSwitch(1, true);
                Constants.tripMode = 1;
                setAnimator(imageView_locate, 0, 0f, 300L, false);
                setAnimator(imageView_hotLine, 0, 0f, 300L, false);
                if (timer != null) {
                    timer.cancel();
                    releaseWakeLock();
                }
            }
            checkUserStatus();

        } else {    //不继续跳转之前的步骤
            imageView_help.setVisibility(View.GONE);
            ad_top_main.setVisibility(View.GONE);
            mes_red_hot.setVisibility(View.GONE);
            if (intent.getBooleanExtra("isLogin", false)) {  //登录后检 查订单状态, 检查true,不检查不传或为false
                isLoadingDone = false;
                hasUnFinishOrder(false);
            } else {
                getTripMode();
                chooseSwitch(Constants.tripMode, true);
                setAnimator(imageView_locate, 0, 0f, 300L, false);
                setAnimator(imageView_hotLine, 0, 0f, 300L, false);
                if (timer != null) {
                    timer.cancel();
                    releaseWakeLock();
                }
            }
        }

    }

    //有车提醒跳转
    private void showHasCarPark(Map<String, String> notifyMap) {
        if ((Constants.tripMode == 2 && (Constants.tripAvai == 3 || Constants.tripAvai == 1)) || (Constants.tripMode == 1 && !layout_place_order.isShown())) {
            chooseSwitch(1, true);
            Constants.tripMode = 1;
            setAnimator(imageView_locate, 0, 0f, 300L, false);
            setAnimator(imageView_hotLine, 0, 0f, 300L, false);
            if (timer != null) {
                timer.cancel();
                releaseWakeLock();
            }

            remindCar = true;
        }
    }

    // 小绿叶
    private void initGreenLeave() {
        //显示使用帮助 小绿叶
        if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) == null) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(imageView_help, "translationY", DensityUtils.dp2px(mContext, 0), DensityUtils.dp2px(mContext, 173));
            animator.setDuration(800).setInterpolator(new BounceInterpolator());
            animator.start();
        }
    }


    //提示打开定位服务
    private void initLocationService() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断定位服务是否开启，如果没有则开启
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) == null) {
                ObjectAnimator animator = ObjectAnimator.ofFloat(imageView_help, "translationY", DensityUtils.dp2px(mContext, 0), DensityUtils.dp2px(mContext, 173));
                animator.setDuration(800).setInterpolator(new BounceInterpolator());
                animator.start();
            }
            startLocation();
        } else {
            final KuaituDialog kuaituDialog = new KuaituDialog(this);
            kuaituDialog.setSingleButton(true);
            kuaituDialog.setTitle(getString(R.string.dialogTitle));
            kuaituDialog.setMessage(getString(R.string.LocationServiceRemind));
            kuaituDialog.setYesOnclickListener("去设置", new KuaituDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, Constants.REQUEST_Location_Service);
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setCancelable(false);
            kuaituDialog.show();
        }
    }

    /**
     * @param type 1点扫码租车(不区分普通车和任务车)，检查完用户资格后，跳转扫码    2任务车点接受任务后，检查完用户资格后，跳转扫码
     */
    private void certifyBikePlaceOrder(final int type) {
        progressBar_mainActivity.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).certifyBikePlaceOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<OperateBean>() {
                    @Override
                    public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            progressBar_mainActivity.setVisibility(View.GONE);
                            //资格正常
                            if (response.body().getStatus() == 200) {
                                if (type == 1) {
                                    requestCode = Constants.REQUEST_SCAN_UNPRE;
                                    intentScan(requestCode);
                                } else if (type == 2) {
                                    requestCode = Constants.REQUEST_SCAN_RED;
                                    intentScan(requestCode);
                                }
                                //资格异常
                            } else if (response.body().getStatus() == 401) { //未交保证金
                                ToastCompat.makeText(mContext, "您还未缴纳保证金", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(mContext, BikeCertificateActivity.class);
                                intent.putExtra("certificateStatus", 401);
                                intent.putExtra(SharedPreferencesKey.IDENTITY_STATUS, response.body().getAttachment().getIdentityStatus());
                                startActivity(intent);
                            } else if (response.body().getStatus() == 403) {  //未实名认证
                                ToastCompat.makeText(mContext, "您还未实名认证", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(mContext, BikeCertificateActivity.class);
                                intent.putExtra("certificateStatus", 403);
                                startActivity(intent);
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<OperateBean> call, Throwable t) {
                        progressBar_mainActivity.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                        Log.i("netError", "009");
                    }
                });
    }

    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }


    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    public static String getAreaCode() {
        return areaCode;
    }

    @Override
    public void remindCar() {
        if (MyApplication.getInstance().getUid() != null) {
            getTopAd();
            getMsgRed();
        }
    }


}